//
//  KINGNetworkTools.swift
//  肉荣微博
//
//  Created by king on 15/7/30.
//  Copyright © 2015年 king. All rights reserved.
//

import UIKit
import AFNetworking
private let KINGNetworkErrorDoMain = "KINGNetworkResponseError"

private enum KINGNetworkType : String {
    case GET = "GET"
    case POST = "POST"
}

private enum KINGNetworkError : Int {
    case responseEmpty = -1
    case tokenEmpty = -2
    
    private var errorDscrption:String {
        switch self {
        case .responseEmpty:
            return "空数据"
        case .tokenEmpty:
            return "token为空"
        }
    }
    
    private func error ()-> NSError {
        return NSError(domain: KINGNetworkErrorDoMain, code: rawValue, userInfo: [KINGNetworkErrorDoMain:errorDscrption])
    }
    
}

class KINGNetworkTools: AFHTTPSessionManager {
    //MARK: - 网络工具单例
    static let sharedTools:KINGNetworkTools = {
        let baseURL = NSURL(string: "https://api.weibo.com/")
        let tools = KINGNetworkTools(baseURL: baseURL)
        //设置响应头的解析器支持格式。。。
        tools.responseSerializer.acceptableContentTypes = ["application/xml", "text/xml", "text/plain", "application/json"]
        return tools
    }()
    //MARK: - 私有数据
    private let appKey = "2202937559"
    private let appSecret = "5376b017dfd694c76982405249b3a455"
    let callBack = "http://www.baidu.com"
    private let grantType = "authorization_code"
    
    func loadURL() -> NSURL {
        return NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(callBack)")!
    }
    //MARK: - 获取授权证书
    func getToken(code:String, finished :KINGNetToolsCallBack) -> () {
        let parameters:[String: AnyObject] = ["client_id" : appKey,
                            "client_secret" : appSecret,
                            "grant_type" : grantType,
                            "code" : code,
                            "redirect_uri" : callBack]
        let url = "https://api.weibo.com/oauth2/access_token"
        //优化网络架构，调用自封装函数，和网络框架隔离开来
        requestMethod(KINGNetworkType.POST, urlString: url, parameters: parameters, finished: finished)
    }
    //MARK: - 发布微博
    func sendStaties(text:String, image:UIImage?, finished:KINGNetToolsCallBack) -> () {
        let urlString = "2/statuses/update.json"
        guard var patameters = tokenDict(finished) else {
            return
        }
        patameters["status"] = text
        if image == nil {
            requestMethod(KINGNetworkType.POST, urlString: urlString, parameters: patameters, finished: finished)
        } else {
            uploadImage("https://upload.api.weibo.com/2/statuses/upload.json", image: image!, parameters: patameters, finished: finished)
        }
    }
    //MARK: - 获取用户名和用户头像
    func loadUserInfo(uid: String, finished: KINGNetToolsCallBack) -> () {
        let urlString = "2/users/show.json"
        //调用抽取的token字典方法
        guard var patameters = tokenDict(finished) else{
            return
        }
        patameters["uid"] = uid
        requestMethod(KINGNetworkType.GET, urlString: urlString, parameters: patameters, finished: finished)
    }
    //获取微博数据
    func loadStatuses(since_id: Int, max_id: Int, finished:KINGNetToolsCallBack) -> () {
        let urlString = "2/statuses/home_timeline.json"
        //调用抽取之后的token字典
        guard var patameters = tokenDict(finished) else{
            //这里不用调用finished的方法，如果为null在token中就返回错误了
            return
        }
        //设置刷新参数
        if since_id > 0 {
            patameters["since_id"] = since_id
        }
        if max_id > 0 {
            patameters["max_id"] = max_id - 1
        }
        print(patameters)
        requestMethod(KINGNetworkType.GET, urlString: urlString, parameters: patameters, finished: finished)
//        requestMethod(KINGNetworkType.GET, urlString: urlString, parameters: patameters) { (result, error) -> () in
//            if error != nil {
//                finished(result: nil, error: error)
//                return
//            }
//            if let array = result!["statuses"] as? [[String : AnyObject]] {
//                for dict in array {
//                    print("\(KINGStatuses(dict: dict))")
//                }
//            } else {
//                finished(result: nil, error: KINGNetworkError.responseEmpty.error())
//            }
//        }
    }
    //获取token字典
    private func tokenDict(finished:KINGNetToolsCallBack)->[String:AnyObject]? {
        guard let userAccent = KINGUserAccount.userAccount else{
            finished(result: nil, error: KINGNetworkError.tokenEmpty.error())
            return nil
        }
        return ["access_token":userAccent.access_token!]
    }
    
    //MARK: - 网络模块封装，以后发出请求统一调用下面的方法
    
    typealias KINGNetToolsCallBack = (result:[String: AnyObject]?, error: NSError?)->()
    //MARK: - 二次网络封装
    private func requestMethod(type:KINGNetworkType, urlString:String, parameters: [String: AnyObject], finished:KINGNetToolsCallBack) {
        let successCallBack:(NSURLSessionDataTask!, AnyObject!) -> Void = { (_, JSON) -> Void in
            if let result = JSON as? [String : AnyObject] {
                finished(result: result, error: nil)
            } else {
                //返回自定义错误
                finished(result: nil, error: KINGNetworkError.responseEmpty.error())
            }
        }
        
        let faildCallBack: (NSURLSessionDataTask!, NSError!) -> Void = { (_, error) -> Void in
            finished(result: nil, error: error)
        }
        
        switch type {
        case .GET:
            GET(urlString, parameters: parameters, success: successCallBack, failure: faildCallBack)
        case .POST:
            POST(urlString, parameters: parameters, success: successCallBack, failure: faildCallBack)
        }
    }
    //MARK: - 上传图片方法
    private func uploadImage(urlString:String, image: UIImage, parameters: [String: AnyObject], finished:KINGNetToolsCallBack) {
        let successCallBack:(NSURLSessionDataTask!, AnyObject!) -> Void = { (_, JSON) -> Void in
            if let result = JSON as? [String : AnyObject] {
                finished(result: result, error: nil)
            } else {
                //返回自定义错误
                finished(result: nil, error: KINGNetworkError.responseEmpty.error())
            }
        }
        
        let faildCallBack: (NSURLSessionDataTask!, NSError!) -> Void = { (_, error) -> Void in
            finished(result: nil, error: error)
        }
        POST(urlString, parameters: parameters, constructingBodyWithBlock: { (fromData) -> Void in
            let data = UIImagePNGRepresentation(image)
            fromData.appendPartWithFileData(data, name: "pic", fileName: "xxoo", mimeType: "application/octet-stream")
            }, success: successCallBack, failure: faildCallBack)
    }
    
}
